package com.shushan.pages;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.Constants;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.bean.MaketingActivityBean;
import com.shushan.pages.bean.MaketingDataBean;
import com.shushan.pages.bean.WXPayBean;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.util.Session;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.ToolUtils;
import com.shushan.util.UmengEventUtil;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.List;

/**
 * @ClassName: OpenVipActivity
 * @Desciption: //分享营销--开通VIP页面
 * @author: zhangshihao
 * @date: 2018-05-22
 */
public class OpenVipActivity extends NavigationLoseActivity implements View.OnClickListener{

    private static final String TAG = "OpenVipActivity";

    private RelativeLayout rlConcessionPrize;
    private Button btnBuyVIP;
    private WebView webViewGuide;
    private TextView tvOriginPrize;
    private TextView tvConcessionsPrize;
    private TextView tvOpenVipNumToday;
    private TextView tvVipRestToday;

    private IWXAPI api;

    private MaketingDataBean maketingDataBean;
    private BabyApplication babyApplication = BabyApplication.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_open_vip);
        setTitle("开通VIP");

        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.registerApp(Constants.APP_ID);

        maketingDataBean = (MaketingDataBean) Session.getSession().get("maketingDataBean");

        initView();

        initWebView();

        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setAllowBack(false);
    }

    private void initView(){
        rlConcessionPrize = findViewById(R.id.rl_concessions_prize);
        rlConcessionPrize.setOnClickListener(this);
        btnBuyVIP = findViewById(R.id.btn_buy_vip);
        btnBuyVIP.setOnClickListener(this);
        webViewGuide = findViewById(R.id.webview_guide);
        tvOriginPrize = findViewById(R.id.tv_origin_prize);
        tvConcessionsPrize = findViewById(R.id.tv_concessions_prize);
        tvOpenVipNumToday = findViewById(R.id.tv_open_vip_num_today);
        tvVipRestToday = findViewById(R.id.tv_vip_rest_today);
    }

    private void initData(){
        MaketingActivityBean maketingActivityBean = maketingDataBean.getMaketingActivityBeanList().get(0);
        tvOriginPrize.setText(maketingActivityBean.cost_price+"");
        tvConcessionsPrize.setText(maketingActivityBean.favorable_price+"");
        tvOpenVipNumToday.setText(maketingActivityBean.sell+"");
        tvVipRestToday.setText(maketingActivityBean.stock+"");
        btnBuyVIP.setText("确认微信支付: "+maketingActivityBean.favorable_price+"元");
    }

    private void initWebView(){
        WebSettings mWebSettings = webViewGuide.getSettings();
        mWebSettings.setSupportZoom(true);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setDefaultTextEncodingName("utf-8");
        mWebSettings.setLoadsImagesAutomatically(true);

        //调用JS方法.安卓版本大于17,加上注解 @JavascriptInterface
        mWebSettings.setJavaScriptEnabled(true);
        webViewGuide.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        webViewGuide.loadUrl("https://tpi.shushan.com/pd.html");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_concessions_prize:
            case R.id.btn_buy_vip:
                setAllowBack(true);
                orderPay();

                UmengEventUtil.onEvent(babyApplication,"vip_buy_click_id");
                break;
        }
    }

    private void orderPay() {
        if(api.getWXAppSupportAPI() < Build.PAY_SUPPORTED_SDK_INT) {
            showToast("您未安装最新版本微信，不支持微信支付，请安装或升级微信版本");
            return;
        }

        List<MaketingActivityBean> maketingBeanList = maketingDataBean.getMaketingActivityBeanList();
        if(ToolUtils.isListEmpty(maketingBeanList)){
            showToast("活动信息为空");
            return;
        }

        MaketingActivityBean maketingActivityBean = maketingBeanList.get(0);
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.PAY_ORDER);
        urlParse.putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("goods_name","限时活动优惠价￥" + maketingActivityBean.favorable_price)
                .putValue("vip_time",maketingActivityBean.vip_time);

        if(BuildConfig.DEBUG){
            urlParse.putValue("money","0.01");
        }else {
            urlParse.putValue("money",maketingActivityBean.favorable_price);
        }

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<WXPayBean>() {

                    @Override
                    protected void onCommon() {
                        super.onCommon();

                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(WXPayBean wxPayBean) {
                        if(wxPayBean != null){
                            PayReq req = new PayReq();
                            req.appId			= wxPayBean.appid;
                            req.partnerId		= wxPayBean.partnerid;
                            req.prepayId		= wxPayBean.prepayid;
                            req.nonceStr		= wxPayBean.noncestr;
                            req.timeStamp		= wxPayBean.timestamp + "";
                            req.packageValue	= wxPayBean.packageName;
                            req.sign			= wxPayBean.sign;
                            req.extData			= "app data"; // optional

                            Log.i(TAG,"out_trade_no=" + wxPayBean.out_trade_no);
                            SharedPreferencesUtils.setStringDate(Constants.OUT_TRADE_NO_SHAREPREFERS_KEY,wxPayBean.out_trade_no);

                            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            api.sendReq(req);
                        }else {
                            showToast("返回数据为空");
                        }

                        onBackAction();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

}
